const fs = require('fs')
const readline = require('readline')
const os = require('os')

const pingReg = new RegExp(/\{\\\"command\\\":\\\"heartbeat-ping\\\",\\\"content\\\":\{\}\}/)
const pongReg = new RegExp(/\\\"\{\\\\\\\"command\\\\\\\":\\\\\\\"heartbeat-pong\\\\\\\",\\\\\\\"content\\\\\\\":\{\}\}\\\"/)
const magicReg = new RegExp(/【magicReport】/)
const ipcPongReg = new RegExp(/收到心跳消息/)

// ./2019-12-17.log
// ./2019-12-14.log
// ./test.log

function isPing (reg, string) {
  return reg.test(string)
}

function splitFile (filePath, outputConfig) {
  // 从某个字符设备创建一个流。
  const stream = fs.createReadStream(filePath, {
    encoding: 'utf8'
  })
  const heartbeatFile = fs.createWriteStream('./heartbeat.log', {
    // encoding: 'utf8'
  })
  const magicFile = fs.createWriteStream('./magic.log')
  const ipcPongFile = fs.createWriteStream('./ipcPong.log')
  const interactionFile = fs.createWriteStream('./interaction.log')

  const rl = readline.createInterface({
    crlfDelay: Infinity,
    input: stream,
    // output: output
  })

  rl.on('line', (input) => {
    if (isPing(pingReg, input)) {
        heartbeatFile.write(input + os.EOL)
        return
    }

    if (isPing(pongReg, input)) {
        heartbeatFile.write(input + os.EOL)
        return
    }

    if (isPing(magicReg, input)) {
        magicFile.write(input + os.EOL)
        return
    }

    if (isPing(ipcPongReg, input)) {
        ipcPongFile.write(input + os.EOL)
        return
    }

    interactionFile.write(input + os.EOL)
    // console.log(`接收到：${input}`)
    // output.write(input, 'utf8')
    // output.write(input)
  })
  rl.on('close', ()=>{
    console.log('readline close...')
  })
}

module.exports = {
  splitFile
}